package com.dzf.controller;

import com.dzf.Util.SessionUtil;
import com.dzf.entity.Blog;
import com.dzf.entity.BlogCont;
import com.dzf.entity.RespJson;
import com.dzf.entity.User;
import com.dzf.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/api/blog/")
public class BlogController {
    @Autowired
    BlogService blogService;
    @Autowired
    SessionUtil sessionUtil;

    /**
     * 添加博客，
     * @param blogCont 博客组合类,包含博客内容和博客标题等
     * @return 请求是否成功
     */
    @RequestMapping("/addBlog")
    @ResponseBody
    public RespJson addBLog(@RequestBody BlogCont blogCont){
        boolean b = blogService.amend(blogCont);
        if (b)
        {
            return RespJson.success(200,"已发表！",b);
        };
        return RespJson.success(417,"发布失败！！",b);
    }

    @RequestMapping("/delBlog")
    @ResponseBody
    public RespJson delBLog(@RequestBody Blog blog){
        boolean b = blogService.delBlogCont(blog);
        if (b)
        {
            return RespJson.success(200,"已发表！",b);
        };
        return RespJson.success(417,"发布失败！！",b);
    }

    /**
     * 发出更新博客的请求，更新博客需要登录才能进行
     * @return addBlog页面
     */
    @RequestMapping("/go2AddBlog")
    public String go2Add()
    {
        return "/blog/addBlog";
    }


    /**
     *  根据 UID 去找到该用户所发布的博客列表
     * @return 博客对象集合
     */
    @RequestMapping("/findAll")
    @ResponseBody
    public RespJson findAll()
    {
        User user = sessionUtil.getUser();
        List<Blog> list = blogService.findAll(user.getId());
        return RespJson.success(200,"ok",list);
    }

    /**
     * 用户登录后使用该方法来获取一个博客的内容
     * @param blogid 博客ID
     * @return 博客对象
     */
    @RequestMapping("/findBlogById/{blogid}")
    @ResponseBody
    public RespJson findBlogById(@PathVariable("blogid")String blogid)
    {
        BlogCont blog = blogService.findById(blogid);
        return RespJson.success(200,"ok",blog);
    }
}
